<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>用promise实现ajax</title>
</head>

<body>
    <script>
        function timeout(ms) {
            return new Promise((resolve, reject) => {
                setTimeout(resolve, ms, "done");
            })
        }
        timeout().then((list_data) => {
            console.log(list_data);
        })
        //用promise实现ajax
        var getJSON = function (url) {
            var promise = new Promise(function (resolve, reject) {
                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = handler;
                xhr.open("GET", url);
                xhr.send();

                function handler() {
                    if (this.readyState == 4) {
                        if (this.status >= 200 && this.status < 300 || this.status == 304) {
                            resolve(this.responseText);
                        } else {
                            reject(new Error(this.statusText));
                        }
                    }
                }


            })
            return promise;
        }
        getJSON("../es6/json/data.json").then(function (json) {
            console.log("success:" + json);
        }, function (error) {
            console.log("error:" + error)
        })
    </script>
</body>

</html>